import { ref } from 'vue';

// 定义类型
export interface SeoDataType {
  title: string;
  description: string;
  keywords: string;
  url: string;
  image: string;
}

export interface PageDataType {
  title?: string;
  description?: string;
  keywords?: string;
  url?: string;
  icon?: string;
  classify?: Array<{
    id: string;
    name: string;
    url: string;
  }>;
  homeConfig?: {
    featured_products?: Array<{
      name: string;
      url: string;
      images?: string[];
      price: number;
    }>;
  };
}

export interface JsonLdType {
  "@context": string;
  "@type": string;
  name: string;
  description: string;
  url: string;
  image: string;
  publisher: {
    "@type": string;
    name: string;
    logo: {
      "@type": string;
      url: string;
    };
  };
  mainEntity?: any;
  significantLink?: any;
}

export class SeoManager {
  private seoData = ref<SeoDataType>({
    title: '',
    description: '',
    keywords: '',
    url: '',
    image: ''
  });
  
  private pageData = ref<PageDataType | null>(null);

  constructor(initialSeoData: SeoDataType) {
    this.seoData.value = initialSeoData;
  }

  // 获取SEO数据
  getSeoData() {
    return this.seoData;
  }

  // 获取页面数据
  getPageData() {
    return this.pageData;
  }

  // 加载页面数据并设置SEO
  async loadPageData(dataPath: string, initialData?: any) {
    try {
      // 尝试加载静态数据
      const response = await fetch(dataPath).catch(() => null);
      let data = null;

      if (response && response.ok) {
        // 如果静态数据可用，使用静态数据
        data = await response.json();
      } else {
        // 否则使用初始化数据
        data = initialData || (window as any).__INITIAL_INDEX__;
      }

      if (data) {
        this.pageData.value = {
          title: data.name || 'LANNUAN - Fashion Shop',
          description: data.description || this.seoData.value.description,
          keywords: data.keywords || this.seoData.value.keywords,
          url: data.url || 'clothings',
          icon: data.category?.icon || '',
          classify: data.classify || [],
          homeConfig: data.homeConfig || {}
        };

        // 更新SEO数据
        this.updateSeoData();
        
        return {
          homeConfig: data.homeConfig,
          homeCategory: data.homeCategory
        };
      }
    } catch (error) {
      // 如果加载失败，尝试使用初始化数据
      const initialData = (window as any).__INITIAL_INDEX__;
      if (initialData) {
        this.pageData.value = {
          title: initialData.name || 'LANNAN - Fashion Shop',
          description: initialData.description || this.seoData.value.description,
          keywords: initialData.keywords || this.seoData.value.keywords,
          url: initialData.url || 'clothings',
          icon: initialData.category?.icon || '',
          classify: initialData.classify || [],
          homeConfig: initialData.homeConfig || {}
        };

        // 更新SEO数据
        this.updateSeoData();
        
        return {
          homeConfig: initialData.homeConfig,
          homeCategory: initialData.homeCategory
        };
      }
    }
    
    return null;
  }

  // 辅助函数：更新Meta标签
  private updateMetaTag(name: string, content: string) {
    let metaTag = document.querySelector(`meta[name="${name}"]`);
    if (!metaTag) {
      metaTag = document.createElement('meta');
      metaTag.setAttribute('name', name);
      document.head.appendChild(metaTag);
    }
    metaTag.setAttribute('content', content);
  }

  // 更新SEO数据
  updateSeoData() {
    if (!this.pageData.value) return;

    // 更新SEO数据
    this.seoData.value = {
      title: this.pageData.value.title || this.seoData.value.title,
      description: this.pageData.value.description || this.seoData.value.description,
      keywords: this.pageData.value.keywords || this.seoData.value.keywords,
      url: `https://lannuan.com/home/${this.pageData.value.url || 'clothings'}.html`,
      image: this.pageData.value.icon || ''
    };

    // 设置页面标题
    document.title = this.seoData.value.title;

    // 设置描述标签
    this.updateMetaTag('description', this.seoData.value.description);

    // 设置关键词标签
    this.updateMetaTag('keywords', this.seoData.value.keywords);

    // 设置规范链接标签
    const canonicalLink = document.querySelector('link[rel="canonical"]') || document.createElement('link');
    canonicalLink.setAttribute('rel', 'canonical');
    canonicalLink.setAttribute('href', this.seoData.value.url);
    if (!document.querySelector('link[rel="canonical"]')) {
      document.head.appendChild(canonicalLink);
    }

    // 设置Open Graph标签
    this.setOpenGraphTags();

    // 添加 JSON-LD 结构化数据
    this.addJsonLdStructuredData();
  }

  // 设置Open Graph标签
  private setOpenGraphTags() {
    const ogTags = {
      'og:title': this.seoData.value.title,
      'og:description': this.seoData.value.description,
      'og:type': 'website',
      'og:url': this.seoData.value.url,
      'og:image': this.seoData.value.image
    };

    // 添加Open Graph标签
    Object.entries(ogTags).forEach(([property, content]) => {
      if (!content) return; // 跳过空值

      let metaTag = document.querySelector(`meta[property="${property}"]`) || document.createElement('meta');
      metaTag.setAttribute('property', property);
      metaTag.setAttribute('content', content as string);
      document.head.appendChild(metaTag);
    });
  }

  // 添加JSON-LD结构化数据
  private addJsonLdStructuredData() {
    if (!this.pageData.value) return;

    // 创建 JSON-LD 结构化数据
    const jsonLd: JsonLdType = {
      "@context": "https://schema.org/",
      "@type": "WebPage",
      "name": this.seoData.value.title,
      "description": this.seoData.value.description,
      "url": this.seoData.value.url,
      "image": this.seoData.value.image,
      "publisher": {
        "@type": "Organization",
        "name": "FRSST",
        "logo": {
          "@type": "ImageObject",
          "url": "https://admin.lannuan.com/static/logo.png"
        }
      }
    };

    // 添加分类数据
    if (this.pageData.value.classify && Array.isArray(this.pageData.value.classify)) {
      jsonLd.mainEntity = {
        "@type": "ItemList",
        "itemListElement": this.pageData.value.classify.map((item, index) => ({
          "@type": "ListItem",
          "position": index + 1,
          "name": item.name,
          "url": `https://lannuan.com/classify/${item.url}-${item.id}.html`
        }))
      };
    }

    // 添加特色商品
    if (this.pageData.value.homeConfig?.featured_products && this.pageData.value.homeConfig.featured_products.length > 0) {
      jsonLd.significantLink = this.pageData.value.homeConfig.featured_products.map(product => ({
        "@type": "Product",
        "name": product.name,
        "url": `https://lannuan.com/product/${product.url}.html`,
        "image": product.images?.[0],
        "offers": {
          "@type": "Offer",
          "price": product.price,
          "priceCurrency": "USD"
        }
      }));
    }

    // 删除现有的JSON-LD脚本
    const existingScript = document.querySelector('script[type="application/ld+json"]');
    if (existingScript) {
      existingScript.remove();
    }

    // 添加新的JSON-LD脚本
    const jsonLdScript = document.createElement('script');
    jsonLdScript.type = 'application/ld+json';
    jsonLdScript.textContent = JSON.stringify(jsonLd);
    document.head.appendChild(jsonLdScript);
  }
}

// 创建SEO管理器实例的工厂函数
export function createSeoManager(initialSeoData: SeoDataType) {
  return new SeoManager(initialSeoData);
} 